package com.ye.reggie.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.ye.reggie.common.R;
import com.ye.reggie.pojo.User;
import com.ye.reggie.service.UserService;
import com.ye.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    /**
     *  移动端发送短信
     *
     * @author 叶旭晖
     * @date 2022/4/27 20:53
     * @param [user, session]
     * @return R<String>
     */
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session){

        //获取手机号
        String phone = user.getPhone();

        if(StringUtils.isNotEmpty(phone)){

            //生成随机的4位验证码
            String code = ValidateCodeUtils.generateValidateCode(4).toString();

            //利用阿里云api发送短信
            log.info("code={}",code);

            //将生成的验证码放入session中
            session.setAttribute(phone,code);

            return R.success("手机验证码发送成功");
        }
        return R.error("手机验证码发送失败");
    }

    /**
     *  移动端登录
     *
     * @author 叶旭晖
     * @date 2022/4/27 20:53
     * @param [map, session]
     * @return R<String>
     */
    public R<User> login(@RequestBody Map map,HttpSession session){

        //获取手机号
        String phone = map.get("phone").toString();
        //获取验证码
        String code = map.get("code").toString();
        //从session中获取验证码
        Object codeInSession = session.getAttribute(phone);
        //比对验证码（session中的和页面获取的）
        if(codeInSession != null && codeInSession.equals(code)){
            //比对成功则登录成功
            //判断用户是否注册，若未注册则创建新用户
            LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();

            lambdaQueryWrapper.eq(User::getPhone,phone);

            User user = userService.getOne(lambdaQueryWrapper);
            if(user == null){
                user = new User();
                userService.save(user);
            }
            session.setAttribute("user",user.getId());
            return R.success(user);
        }
        return R.error("短信发送失败");
    }

}
